<template>
	<view class="container">
		<view class="formBox">
			<uni-forms ref="form" :modelValue="form" :rules="rules">
				<view class="box">
					<uni-forms-item required label="分组名称" name="group_name">
						<uni-easyinput type="text" v-model="form.group_name" :clearable="false" placeholder="请输入分组名称" />
					</uni-forms-item>
					<uni-forms-item label="排序" name="sort">
						<uni-number-box v-model="form.sort" />
					</uni-forms-item>
					<uni-forms-item label="状态" name="status">
						<switch :checked="form.status == 1" @change="switchChange" color="#2979ff" />
					</uni-forms-item>
				</view>
				<view class="btns">
					<button class="btn" type="primary" @click="submit">确定</button>
				</view>
			</uni-forms>
		</view>
	</view>
</template>

<script>
import api from '@/api/api';
export default {
	data() {
		return {
			id: null,
			type: 'detail',
			form: {
				group_name: '',
				sort: 0,
				status: 1
			},
			rules: {
				group_name: {
					rules: [
						{
							required: true,
							errorMessage: '请填写分组名称'
						}
					]
				}
			}
		};
	},
	onLoad(e) {
		if (e.id) {
			this.id = e.id;
			this.type = 'detail';
			uni.setNavigationBarTitle({
				title: '分组信息'
			});
			this.getDetail();
		} else {
			this.type = 'add';
			uni.setNavigationBarTitle({
				title: '新增分组'
			});
		}
	},
	methods: {
		switchChange(e) {
			if (e.detail.value) {
				this.form.status = 1;
			} else {
				this.form.status = 0;
			}
		},
		submit() {
			this.$refs.form.validate().then((res) => {
				console.log(res);
				if (this.type == 'detail') {
					res.id = this.id;
					api.editGroup(res).then((data) => {
						if (data.data.is_success) {
							uni.showToast({
								title: '修改成功'
							});
							setTimeout(() => {
								uni.navigateBack();
							}, 500);
						} else {
							uni.showToast({
								title: '数据未修改',
								icon: 'none'
							});
						}
					});
				} else if (this.type == 'add') {
					api.addGroup(res).then((data) => {
						if (data.data.is_success) {
							uni.showToast({
								title: '添加成功'
							});
							setTimeout(() => {
								uni.navigateBack();
							}, 500);
						}
					});
				}
			});
		},
		getDetail() {
			api.groupDetail({ id: this.id }).then((res) => {
				this.form.group_name = res.data.info.group_name;
				this.form.sort = res.data.info.sort;
				this.form.status = res.data.info.status;
			});
		}
	}
};
</script>